package com.youzikj.wx.comm.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.util.Date;
import java.util.Map;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;

import com.youzikj.wx.comm.Singleton;
import com.youzikj.wx.comm.pojo.Token;
import com.youzikj.wx.comm.x509Trust.MyX509TrustManager;

/**
 * 通用工具类
 * @author Administrator
 *
 */
public class CommonUtil {
	
	private static Logger log = Logger.getLogger(CommonUtil.class);
	
	public  static final String  appId = "wxca78deeb014de180";
	
	public static final String  appSecret = "1571230c181e897c0f0a492d1e2aa47c";
	
	//凭证获取地址
	public final static String token_url ="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
	
	//获取jsapi_ticket
	public final static String ticket_url="https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi";
	/**
	 * 发送https请求
	 * @param requestUrl 请求地址
	 * @param requestMethod 请求方式（get,post）
	 * @param outputStr 提 交的数据
	 * @return JSONObject
	 */
	public static JSONObject httpsRequest(String requestUrl, String requestMethod, String outputStr){
		JSONObject jsonObject = null;
		try {
			//创建SSLContext对象,并使用我们指定的信任管理器初始化
		   TrustManager[] tm ={new MyX509TrustManager()};
		   SSLContext sslContext = SSLContext.getInstance("SSL","SunJSSE");
		   sslContext.init(null, tm, new java.security.SecureRandom());
		   //获得SSLSocketFactory对象
		   SSLSocketFactory ssf = sslContext.getSocketFactory();
		   
		   URL url = new URL(requestUrl);
		   HttpsURLConnection conn = (HttpsURLConnection)url.openConnection();
		   conn.setSSLSocketFactory(ssf);
		   
		   conn.setDoOutput(true);
		   conn.setDoInput(true);
		   conn.setUseCaches(false);
		   //设置请求方式
		   conn.setRequestMethod(requestMethod);
		   //当outputstr不为null时，向输出流写数据
		   if(null != outputStr){
			   OutputStream outputStream = conn.getOutputStream();
			   outputStream.write(outputStr.getBytes("UTF-8"));
			   outputStream.close();
		   }
		   //从输入流读取返回内容
		   InputStream inputStream = conn.getInputStream();
		   InputStreamReader inputStreamReader = new InputStreamReader(inputStream,"UTF-8");
		   BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
		   String str = null;
		   StringBuffer buffer = new StringBuffer();
		   while((str = bufferedReader.readLine()) != null){
			   buffer.append(str);
		   }
		   //释放资源
		   bufferedReader.close();
		   inputStreamReader.close();
		   inputStream.close();
		   inputStream = null;
		   conn.disconnect();
		   jsonObject = JSONObject.fromObject(buffer.toString());
		} catch (Exception e) {
			log.error("https请求异常：{}", e);
		}
		return jsonObject;
	}
	
	public static Token getToken(String appid, String appsecret){
		Token token = null;
		String requestUrl = token_url.replace("APPID", appid).replace("APPSECRET", appsecret);
		//发送get获取凭证
		JSONObject jsonObject = httpsRequest(requestUrl, "GET", null);
		if(null != jsonObject){
			try {
				token = new Token();
				token.setAccessToken(jsonObject.getString("access_token"));
				token.setExpiresIn(jsonObject.getInt("expires_in"));
			} catch (Exception e) {
				token = null;
				log.error("获取token失败 errcode:"+jsonObject.getInt("errcode")+"errmsg:"+jsonObject.getString("errmsg"));
			}
		}
		return token;
	}
	
	public static String getJsapiTicket(String token){
		String jst= null;
		String requestUrl = ticket_url.replace("ACCESS_TOKEN", token);
		//发送get获取凭证
		JSONObject jsonObject = httpsRequest(requestUrl, "GET", null);
		if(null != jsonObject){
			try {
				jst = jsonObject.getString("ticket");
			} catch (Exception e) {
				token = null;
				log.error("获取JsapiTicket失败 errcode:"+jsonObject.getInt("errcode")+"errmsg:"+jsonObject.getString("errmsg"));
			}
		}
		return jst;
	}
	
	public static String getSingToken(String appid,String appsecret){
		String result = "";
		Singleton singleton = Singleton.getInstance();
		Map<String, String> map = singleton.getMap();
		String time = map.get("time");
		String accessToken = map.get("access_token");
		Long nowDate = new Date().getTime();
		//这里设置过期时间 3000*1000就好了
		if (accessToken != null && time != null && nowDate - Long.parseLong(time) < 3000 * 1000) {
			result = accessToken;
		} else {
			String at =getToken(appid,appsecret).getAccessToken();
			map.put("time", nowDate + "");
			map.put("access_token", at);
			result = at;
			}
		return result;
	}
	
	public static String getSingJsapiTicket(String access_token){
		String result = "";
		Singleton singleton = Singleton.getInstance();
		Map<String, String> map = singleton.getMap();
		String time = map.get("time1");
		String Jsapi_ticket = map.get("Jsapi_ticket");
		Long nowDate = new Date().getTime();
		//这里设置过期时间 3000*1000就好了
		if (Jsapi_ticket != null && time != null && nowDate - Long.parseLong(time) < 3000 * 1000) {
			result = Jsapi_ticket;
		} else {
			String jst = getJsapiTicket(access_token);
			map.put("time1", nowDate + "");
			map.put("Jsapi_ticket", jst);
			result = jst;
			}
		return result;
	}
	
}
